For counting loops it is best to use an integer for
the loop control variable.
However,
it is legal to use a floating point control variable and to use fractional increments.
The following program prints a table that displays
x
and ln(x)
for values of
x
from 0.1 up to about 2.0:
class LogTable { public static void main ( String[] args ) { System.out.println( "x" + "\t ln(x)" ); for ( double x = 0.1; x <= 2.0; x = x + 0.1 ) System.out.println( x + "\t" + Math.log( x ) ); } }
It compiles correctly, and runs. But its output is not pretty:
x ln(x) 0.1 -2.3025850929940455 0.2 -1.6094379124341003 0.30000000000000004 -1.203972804325936 0.4 -0.916290731874155 0.5 -0.6931471805599453 0.6 -0.5108256237659907 0.7 -0.35667494393873245 0.7999999999999999 -0.22314355131420985 0.8999999999999999 -0.1053605156578264 0.9999999999999999 -1.1102230246251565E-16 1.0999999999999999 0.09531017980432474 1.2 0.1823215567939546 1.3 0.26236426446749106 1.4000000000000001 0.336472236621213 1.5000000000000002 0.40546510810816455 1.6000000000000003 0.47000362924573574 1.7000000000000004 0.5306282510621706 1.8000000000000005 0.5877866649021193 1.9000000000000006 0.641853886172395
Remember (from a previous chapter) that floating point numbers are not always exact.
In particular, 0.1 is always slightly wrong when represented using floating point,
no matter how many bits are used.
In the above program, errors in x
accumulate,
and x
drifts away from the desired value.
Notice that the
the loop does not end with
x
equal to 2.0, as you would expect.
The loop condition is x <= 2.0
,
but x
evidently overshoots the value 2.0
the last time it is incremented.
Are integer numbers completely accurate?